package com.lyy;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.Set;

/**
 * @author Liangyaoyun
 */
public class JedisSentinelUtil {
    /*
    * Jedis链接池配置实例
    * */
    private static final JedisPoolConfig JEDIS_POOL_CONFI;

    /*
    * 哨兵模式:Jedis链接池
    * */
    private static JedisSentinelPool jedisSentinelPool;

    /*
    * 哨兵模式:全部哨兵节点端口号，逗号分隔
    * */
    private static final Set<String>SENTiMEL_NODES
            =Set.of("192.168.159.77:27001","192.168.159.77:27002","192.168.159.77:27003");

    /*
    * 哨兵模式:哨兵节点所监控的主从结构名称
    * */
    private static final String MONITOR="x";

    static {
        // 初始化Jedis连接池的配置实例
        JEDIS_POOL_CONFI = new JedisPoolConfig();
        // Jedis连接池最多容纳8个连接
        JEDIS_POOL_CONFI.setMaxTotal(8);
        // Jedis连接池最大阻塞时间10s
        JEDIS_POOL_CONFI.setMaxWaitMillis(10000);
        // Jedis连接池最大空闲8个连接
        JEDIS_POOL_CONFI.setMaxIdle(8);
        // Jedis连接池最小空闲0个连接
        JEDIS_POOL_CONFI.setMinIdle(0);
    }

    /**
     *  从Jedis链接池中获取并返回一个单机Jedis链接
     *
     * @return 一个jedis链接
     */

    public static Jedis getJedis(){
        if (null==jedisSentinelPool){
            jedisSentinelPool=new JedisSentinelPool(MONITOR,SENTiMEL_NODES,JEDIS_POOL_CONFI);
        }
        return jedisSentinelPool.getResource();
    }
}
